package db

import (
	"database/sql"
	"fmt"
)

func RowToMap(row *sql.Rows) map[string]string {
	if !row.Next() {
		return nil
	}
	return rowToMap(row)
}

// 结构转换为map
func rowToMap(row *sql.Rows) map[string]string {
	var result = make(map[string]string)
	columns, err := row.Columns()
	if err != nil {
		panic(err)
	}
	values := make([]interface{}, len(columns))
	valuePtrs := make([]interface{}, len(columns))
	for i := range columns {
		valuePtrs[i] = &values[i]
	}
	if err := row.Scan(valuePtrs...); err != nil {
		panic(err)
	}
	for i, col := range columns {
		//如果是nil,则跳过
		value := values[i]
		if value == nil {
			continue
		}
		//判断类型
		switch value.(type) {
		case []uint8:
			s := string(value.([]uint8))
			if s == "" {
				continue
			}
			result[col] = s
		case int64:
			result[col] = fmt.Sprintf("%d", value)
		default:
			panic("未知类型:" + fmt.Sprintf("%T", value))
		}
	}
	return result
}
func RowsToMap(rows *sql.Rows) []map[string]string {
	var result []map[string]string
	for rows.Next() {
		result = append(result, rowToMap(rows))
	}
	return result
}
